#include "Mesh.hpp"
#include <fstream>
#include "OffFile.hpp"
#include <string>
#include "PolyMesh.hpp"
#include "GeometryBuffer.hpp"

using namespace std;
//
//bool OffFile::Read(const std::string aFileName,
//                   PolyhedraMesh&        aMesh)
//{
//   ifstream f(aFileName.c_str());
//   std::string offStr;
//   f >> offStr;
//   if (offStr != "OFF")
//   {
//      return false;
//   }
//   int vertCount, tetCount, otherCount;
//   f >> vertCount >> tetCount >> otherCount;
//
//   aMesh.tetra.resize(tetCount);
//   aMesh.verts.resize(vertCount);
//
//   for (size_t i = 0; i < vertCount; ++i)
//   {
//      float x,y,z;
//      f >> x >> y >> z;
//      aMesh.verts[i].set(x,y,z);
//   }
//   for (size_t i = 0; i < tetCount; ++i)
//   {
//      Tetra& t = aMesh.tetra[i];
//      f >> t.vertex[0] >> t.vertex[1] >> t.vertex[2] >> t.vertex[3];
//   }
//   return true;
//}

bool OffFile::Read(const std::string aFileName,
                   Mesh&             aMesh)
{
   ifstream f(aFileName.c_str());
   std::string offStr;
   f >> offStr;
   if (offStr != "OFF")
   {
      return false;
   }
   size_t vertCount, faceCount, otherCount;
   f >> vertCount >> faceCount >> otherCount;

   aMesh.faces->resize(faceCount);
   aMesh.verts->resize(vertCount);

   for (size_t i = 0; i < vertCount; ++i)
   {
      float x,y,z;
      f >> x >> y >> z;
      aMesh.verts[i].set(x,y,z);
   }
   for (size_t i = 0; i < faceCount; ++i)
   {
      Face& t = aMesh.faces[i];
      int vCount;
      f >> vCount;
      f >> t.vertex[0] >> t.vertex[1] >> t.vertex[2];
   }
   return true;
}

void OffFile::Write(const std::string aFileName,
                    Mesh&             aMesh)
{
   ofstream f(aFileName.c_str());
   f << "OFF \n";
   f << aMesh.verts.size() << ' ' << aMesh.faces.size() << " 0\n";

   for (size_t i = 0; i < aMesh.verts.size(); ++i)
   {
      Vec3 v = aMesh.verts[i];
      f << v.x << ' ' << v.y << ' ' << v.z << '\n';
   }
   for (size_t i = 0; i < aMesh.faces.size(); ++i)
   {
      Face& face = aMesh.faces[i];
      f << "3 " << face.vertex[0] << " " << face.vertex[1] << " " << face.vertex[2] << '\n';
   }
}
